String.prototype.replaceAll = function (searchValue, replaceValue, ignoreCase) {
    searchValue = searchValue.replace(/\$/g, '\\$').replace(/\^/g, '\\^').replace(/\+/g, '\\+').replace(/\?/g, '\\?').replace(/\*/g, '\\*').replace(/\./g, '\\.');
    return this.replace(new RegExp(searchValue, (ignoreCase ? "gi" : "g")), replaceValue);
}
/**
 * 功能：页面HTML加载
 * @url 页面url
 * @data 搜索参数序列化对象
 * @$pageListPanel 页面HTML容器，默认为$("#htmlContainer")
*/
function loadPage(url,data,$pageListPanel) {
	var _url=url;
	_url += url.indexOf("?") == -1 ? "?" : "&";
	_url += "timer=" + new Date().getTime();
	var $panel = $pageListPanel || $("#htmlContainer");
	//$panel.html($("<img src='/static/img/sys/loading.gif'/>")
	//.css({position:"relative",left:($panel.width()-150)/2,top:200}));
	$.jBox.tip("数据加载中...请稍候...", "loading");
	$.ajax({
		type: "POST",
		url: url,
		data:data,
		dataType: "html",
		success:function(data){
			$panel.html(data);
			$.jBox.closeTip();
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
			$.jBox.closeTip();
			$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">程序异常，请联系管理员！</p>',"操作提示！");
			//$panel.html(XMLHttpRequest.responseText);
		}
	});
}

function loadPageDownload(url, data) {
	data=decodeURIComponent(data.replace(/\+/g, '%20'));
	// 获得url和data
	if( url && data ){
		// data 是 string 或者 array/object
		data = typeof data == 'string' ? data : jQuery.param(data);
		// 把参数组装成 form的  input
		var inputs = '';
		jQuery.each(data.split('&'), function(){
			var pair = this.split('=');
			inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />';
		});
		// request发送请求
		jQuery('<form action="'+ url +'" method="post">'+inputs+'</form>')
			.appendTo('body').submit().remove();
	}
}

function loadFramePage(url){
	url += url.indexOf("?") == -1 ? "?" : "&";
	url += "timer=" + new Date().getTime();
	$("#htmlContainer").html($("<img src='/static/img/sys/loading.gif' id='loading_img'/>").css({position:"absolute",left:"45%",top:210}));
	
	var iframe = document.createElement("iframe");
	iframe.frameBorder = "0";
	iframe.scrolling = "auto";
	iframe.id = "framePage";
	iframe.width = "100%";
	iframe.height = $("#navBar").height() - 42;
	
	iframe.src = url;
	$(iframe).appendTo("#htmlContainer");
	
	if (iframe.attachEvent){
	    iframe.attachEvent("onload", function(){
	    	$("#loading_img").remove();
	    });
	} else {
	    iframe.onload = function(){
	    	$("#loading_img").remove();
	    };
	}
}

/**
 * AJAX提交返回JSON格式数据
 * @param option
 */
function ajaxSubmitJson(option){
	$.jBox.tip("加载中……","loading");
	var $btn=option.$btn || null;
	if($btn!=null && $btn.length>0){
		$btn.prop("disabled",true);
	}
	$.ajax({
		type: option.type || 'POST',
		url: option.url,
		data: option.data,
		dataType: 'json',
		cache: false,
		success: function(data){
			$.jBox.closeTip();
			if(data.status == 403){
				if($btn!=null && $btn.length>0){
					$btn.prop("disabled",false);
				}
				$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">'+data.message+'</p>',"操作提示！");
			}else if(data.status == 300){
				$.jBox.closeTip();
				$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">'+data.message+'</p>',"操作提示！", {closed:function(){
					window.location.href = "/login/sys";
				}});
			}else if(data.retCode == 'FAIL' || data.retCode == 'fail'){
				if($btn!=null && $btn.length>0){
					$btn.prop("disabled",false);
				}
				if ($.isFunction(option.failCallback)){
					option.failCallback(data);
				}else{
					$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">'+data.msg+'</p>',"操作提示！");
				}
			}else if(data.retCode == 'SUCCESS' || data.retCode == 'success'){
				if ($.isFunction(option.callback)){
                    option.callback(data);
                }else{
                    $.jBox.tip(data.msg, "success", {timeout:2500});
                }
			}
		},
		error: function(xhr, ajaxOptions, thrownError){
			if($btn!=null && $btn.length>0){
				$btn.prop("disabled",false);
			}
			$.jBox.closeTip();
			$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">程序异常，请联系管理员！</p>',"操作提示！");
		}
	});
}


/**
 * 用bizRetVo返回时调用
 * @param option
 */
function ajaxByBizretVo(option){
	$.ajax({
		type: option.type || 'POST',
		url: option.url,
		data: option.data,
		dataType: 'json',
		cache: false,
		success: function(data){
			if(data.status == 403){
				$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">"+data.message+"</p>',"操作提示！");
			}else if(data.status == 300){
				$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">"+data.message+"</p>',"操作提示！", { closed:function(){
					window.location.href = "/login/sys";
				}});
			}else if(data.bizRetVo.retCode.toUpperCase() == 'FAIL'){
				if ($.isFunction(option.failCallback)){
					option.failCallback(data);
				}else if ($.isFunction(option.callback)){
					option.callback(data);
				}else{
					$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">"+data.bizRetVo.msg+"</p>',"操作提示！");
				}
			}else if(data.bizRetVo.retCode.toUpperCase() == 'SUCCESS'){
				if ($.isFunction(option.callback)){
					option.callback(data);
				}else{
					$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">"+data.bizRetVo.msg+"</p>',"操作提示！");
				}
			}
		},
		error: function(xhr, ajaxOptions, thrownError){
			$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">程序异常，请联系管理员！</p>',"操作提示！");
		}
	});
}

/**
 * 用bizRetVo返回时调用
 * @param option
 */
function ajaxByBizResult(option){
	$.ajax({
		type: option.type || 'POST',
		url: option.url,
		data: option.data,
		dataType: 'json',
		success: function(thisData){
			 if(thisData.retCode=='fail'){
				 $.jBox.tip(thisData.msg, "error", {timeout:1500});
				if ($.isFunction(option.failCallback)){
					setTimeout(function(){
						option.failCallback(thisData);
					},2000)

				}else if ($.isFunction(option.callback)){
					setTimeout(function(){
						option.callback(thisData);
					},2000)

				}
			}else {
				 $.jBox.tip(thisData.msg, "success", {timeout:1500});
				if ($.isFunction(option.callback)){
					setTimeout(function(){
						option.callback(thisData);
					},2000)

				}
			}
		},
		error: function(xhr, ajaxOptions, thrownError){
			$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">程序异常，请联系管理员！</p>',"操作提示！");
		}
	});
}
function selectMenuNode(id, div) {
	$("li", $("#" + div)).removeClass("curSelectedNode");
	$('#' + id).addClass("curSelectedNode");
}

function jumpPage(pageNo) {
	$("#pageNo").val(pageNo);
	var param = $("#form").serialize();
	loadPage($('#form').attr('action'), param);
}

function sort(orderBy, defaultOrder) {
	if ($("#orderBy").val() == orderBy) {
		if ($("#order").val() == "") {
			$("#order").val(defaultOrder);
		}
		else if ($("#order").val() == "desc") {
			$("#order").val("asc");
		}
		else if ($("#order").val() == "asc") {
			$("#order").val("desc");
		}
	}
	else {
		$("#orderBy").val(orderBy);
		$("#order").val(defaultOrder);
	}
	var param = $("#form").serialize();
	loadPage($('#form').attr('action'), param);
	//$("#form").submit();
}

function checkAll(id, name) {
	if(typeof name == 'undefined'){
		name = 'checkRow';
	}
	if (id.checked) {
		$("input[name='"+name+"']").prop("checked", true);
	} else {
		$("input[name='"+name+"']").prop("checked", false);
	}
}

function checkAllBtn() {
	if( document.getElementById('chkAll').checked ) {
		$("input[type='checkbox']").prop("checked", false);
	} else {
		$("input[type='checkbox']").prop("checked", true);
	}
}

function getCheckId(name) {
	if(typeof name == 'undefined'){
		name = 'checkRow';
	}
	var checks = $("input[name='"+name+"']").filter(":checked");
	if(checks.length < 1)  {
		alert("请选择一条数据!");
		return "";
	}
	
	if(checks.length > 1)  {
		alert("最多只能选择一条数据!");
		return "";
	}
	return checks.val();
}

function getCheckIds(name){
	if(typeof name == 'undefined'){
		name = 'checkRow';
	}
	var checks = $("input[name='"+name+"']").filter(":checked");
	if(checks.length < 1)  {
		return "";
	}
	var checkId = [];
	checks.each(function(){ 
		checkId.push($(this).val());
	}); 
	return checkId.join(',');
}

function checkAllSubmit(url, reload) {
	var checks = $("input[name=checkRow]").filter(":checked");
	if(checks.length < 1)  {
		alert("请最少选择一条数据!");
		return;
	}
	if(!confirm("确认执行此操作吗?")) {
		return;
	}
	var param = $("#form").serialize();
	$.ajax({
		type : "POST",
		url : url,
		dataType : "json",
		data : param,
		success : function(data) {
			if (data.ok == 1) {
				alert("删除成功!");
				loadPage(reload);
			} else {
				alert("删除失败!");
			}
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
			$("#htmlContainer").html(XMLHttpRequest.responseText);
		}
	});
}

function checkEdit() {
	var id = getCheckId();
	if(id != "")
		edit(id);
}

function getProperty(pv){
	for(var i=0;i<properties.length;i++){
		if(properties[i].id==pv)
			return properties[i].name;
	}
	return '';
}
function getIndustry(iv){
	for(var i=0;i<industries.length;i++){
		if(industries[i].id==iv)
			return industries[i].name;
	}
	return '';
}

function isUndefined(obj) {
	if(typeof(obj)!="undefined" && obj!=null) {
		return true;
	}
	return false;
}

function compareDate(startDate,endDate){
	if(startDate && endDate && startDate.length>0 && endDate.length>0){
		var s = startDate.split('-');
		var e = endDate.split('-');
		if(s.length==3 && e.length==3){
			var start = new Date(s[0],s[1],s[2]);
			var end = new Date(e[0],e[1],e[2]);
			if(start > end)
				return false;
			else
				return true;
		}
	}
	return true;
}

/*!
 * 功能：地区联动
 * boxId:省市数据josn文件路径
 * prov:默认省份
 * city:默认城市
 * dist:默认地区（县）
 * nodata:无数据状态
 * required:必选项
 * distAll:全市范围
*/
var selectArea=function(options){
	var defaults={
		boxId:"areaBox",
		prov:null,
		city:null,
		dist:null,
		nodata:null,
		hasSuffix:true,
		fv:"id",
		required:true,
		distAll:false,
		callback:function(){}
	};
	var settings = $.extend({}, defaults, options);
	var box_obj=$("#"+settings.boxId);
	var prov_obj=box_obj.find(".prov");
	var city_obj=box_obj.find(".city");
	var dist_obj=box_obj.find(".dist");
	var title="name";
	var defText="请选择";
	if(typeof resumeLang === "string" && resumeLang=="en"){
		title="en";
		defText="select"
	}
	
	var select_prehtml=(settings.required) ? "" : "<option value=''>"+defText+"</option>";
	var dataCity=datajson.City;
	var dist=datajson.town;
	
	var suffix="";
	var suffixV="";
	
	if(settings.fv=="name"){
		settings.fv=title;
	}else{
		settings.fv="id";
	}
	
	var getSuffix=function(s){
		var suffix="";
		if(settings.hasSuffix){
			suffix=s;
			if(typeof resumeLang === "string"){
				suffix=resumeLang=="cn"?s:"";
			}
		}
		return suffix;
	};
	
	//获取地区全称，主要是兼容新旧数据处理
	var getAllName = function(v,arrSuff){
		var hasSuff=false;
		var allName=v;
		if(v==null || v==""){
			return "";
		}
		//判断是否有后缀
		/*for(var i in arrSuff){
			if(v.indexOf(arrSuff[i])!=-1){
				hasSuff=true;
				break;
			}
		}*/
		//无后缀时找出其后缀
		if(!hasSuff){
			for(var key in dataCity){
				if(dataCity[key].name==v){
					allName=v+dataCity[key].s;
					break;
				}
			}
		}
		return allName;
	};
	
	var init=function(){
		// 遍历赋值省份下拉列表
		temp_html=select_prehtml;
		
		//for(var key in dataCity){
		for(k=0; k<dataCity.length; k++){
			if(dataCity[k].id.toString().substr(2,2) == "00" && dataCity[k].s!=""){
				temp_html+='<option value="'+dataCity[k][settings.fv]+'" data-id="'+dataCity[k].id+'">'+dataCity[k][title]+'</option>';
			}
		}
		prov_obj.html(temp_html);

		// 若有传入省份与市级的值，则选中。（setTimeout为兼容IE6而设置）
		t && clearTimeout(t);
		var t=setTimeout(function(){
			if(settings.prov!=null){
				prov_obj.val(settings.prov);
				cityStart();
				setTimeout(function(){
					if(settings.city!=null){
						var defCity=getAllName(settings.city,["市","地区","州"]);
						city_obj.val(defCity);
						distStart();
						setTimeout(function(){
							if(settings.dist!=null){
								dist_obj.val(settings.dist);
								settings.callback();
							};
						},1);
					};
				},1);
			};
		},1);
	
		// 选择省份时发生事件
		prov_obj.unbind("change",cityStart);
		prov_obj.bind("change",cityStart);

		// 选择市级时发生事件
		city_obj.unbind("change",distStart);
		city_obj.bind("change",distStart);


	};
	

	
	// 赋值市级函数
	var cityStart=function(){
		var prov_id=common.getSelectedAttr(prov_obj,"data-id") || 0;
		city_obj.empty().attr("disabled",true);
		dist_obj.empty().attr("disabled",true);
		if(prov_id <= 0){
			if(settings.nodata=="none"){
				city_obj.css("display","none");
				dist_obj.css("display","none");
			}else if(settings.nodata=="hidden"){
				city_obj.css("visibility","hidden");
				dist_obj.css("visibility","hidden");
			};
			return;
		}
		//common.log(prov_id)
		// 遍历赋值市级下拉列表
		temp_html=select_prehtml;
		if( parseInt(prov_id.substr(0,4),10) >=4100 || parseInt(prov_id.substr(0,4),10) <=1300){
			for(var key in dataCity){
				if(dataCity[key].id ==prov_id && dataCity[key].s!=""){
					temp_html+='<option value="'+dataCity[key][settings.fv]+getSuffix(dataCity[key].s)+'" data-id="'+dataCity[key].id+'">'+dataCity[key][title]+getSuffix(dataCity[key].s)+'</option>';
				}
			}
		}else{
			var i=0;
			//for(var key in dataCity){
			for(k=0; k<dataCity.length; k++) {
				if(dataCity[k].id.toString().substr(0,2) == prov_id.toString().substr(0,2) && dataCity[k].id !=prov_id && dataCity[k].s!=""){
					temp_html+='<option value="'+dataCity[k][settings.fv]+getSuffix(dataCity[k].s)+'" data-id="'+dataCity[k].id+'">'+dataCity[k][title]+getSuffix(dataCity[k].s)+'</option>';
					i++;
				}
			}
			if(i==0){
				if(settings.nodata=="none"){
					city_obj.css("display","none");
					dist_obj.css("display","none");
				}else if(settings.nodata=="hidden"){
					city_obj.css("visibility","hidden");
					dist_obj.css("visibility","hidden");
				};
			}		
		}
		
		city_obj.html(temp_html).attr("disabled",false).css({"display":"","visibility":""});
		distStart();
	};
	// 赋值地区（县）函数
	var distStart=function(){
		var prov_id=common.getSelectedAttr(prov_obj,"data-id");
		var city_id=common.getSelectedAttr(city_obj,"data-id");

		dist_obj.empty().attr("disabled",true);

		if(!prov_id>0||!city_id>0){
			if(settings.nodata=="none"){
				dist_obj.css("display","none");
			}else if(settings.nodata=="hidden"){
				dist_obj.css("visibility","hidden");
			};
			return;
		};
		
		// 遍历赋值市级下拉列表
		temp_html=select_prehtml;
		var i=0;
		//for(var key in dist){

		if(settings.distAll){
			temp_html = '<option value="'+city_id+'" data-id="'+city_id+'">全市范围</option>';
		}
		for(k=0; k<dist.length; k++) {
			if(dist[k].id.toString().substr(0,4) == city_id.toString().substr(0,4)){
				temp_html+='<option value="'+dist[k][settings.fv]+'" data-id="'+dist[k].id+'">'+dist[k][title]+'</option>';
				i++;
			}
		}
		if(i==0){
			if(settings.nodata=="none"){
				dist_obj.css("display","none");
			}else if(settings.nodata=="hidden"){
				dist_obj.css("visibility","hidden");
			};
			return;
		}
		dist_obj.html(temp_html).attr("disabled",false).css({"display":"","visibility":""});
//		dist_obj.val(settings.dist);
	};
	init();
};

//初始化民族
function initNationSelect(id) {
	initSingleSelect(id, datajson.nation, "name");
}

//初始化学历选择项
function initDegreeSelect(id) {
	initSingleSelect(id, datajson.degree);
}

//初始化公司性质
function initComTypeSelect(id) {
	initSingleSelect(id, datajson.comType);
}

//初始化公司行业
function initComCallingSelect(id) {
	initSingleSelect(id, datajson.industry);
}

//初始化工作待遇
function initSalarySelect(id) {
	initSingleSelect(id, datajson.salary);
}

//初始化工作年限
function initJobYearSelect(id) {
	initSingleSelect(id, datajson.workyear);
}

//初始化到岗时间
function initCheckindateSelect(id) {
	initSingleSelect(id, datajson.workTime);
}

//初始化单个下拉列表
function initSingleSelect(id, data, fv) {
	fv = fv || "id";
	var select = $("#" + id).get(0);
	select.options.add(new Option("请选择",""));
	for(var key=0; key<data.length; key++) {
	//for(var key in data) {
		select.options.add(new Option(data[key].name, data[key][fv]));
	}
}

//初始化职位选择控件
function initJobSelect(boxId, fv, mDefaultSelect, cDefaultSelect, selectroot) {
	initCorrelationSelect(boxId, fv, datajson.jobFun, "jobTtile", "jobFun", mDefaultSelect, cDefaultSelect, selectroot);
}

//初始化语言水平选择控件
function initLanguageSelect(boxId, fv) {
	initCorrelationSelect(boxId, fv, datajson.language, "type", "level", true, true);
}

//初始化二级联动列表
/**
 * boxId 
 * 
 */
function initCorrelationSelect(boxId, fv, data, mainSelect, childSelect, mDefaultSelect, cDefaultSelect, selectroot) {
	var boxDiv = $("#" + boxId);
	var mSelect = boxDiv.find("." + mainSelect);
	var cSelect = boxDiv.find("." + childSelect);
	//是否允许选择根节点
	var selRoot = typeof(selectroot) == "undefined" ? false : selectroot;
	
	var init=function(){
		mSelect.bind("change",function(){
			loadChildn();
		});
		loadMan();
	};
	
	//初始化职位大类列表
	var loadMan=function() {
		//是否有莫默认选择项
		if(mDefaultSelect) {
			mSelect.get(0).options.add(new Option("请选择",""));
		}
		for(var key=0; key< data.length; key++) {
		//for(var key in data) {
			if(data[key].id.toString().substr(2,4) == "00") {
				mSelect.get(0).options.add(new Option(data[key].name, data[key].id));
			}
		}
	};
	//初始化职位小类
	var loadChildn=function() {
		var elementHtml = "";
		//清空列表
		cSelect.get(0).options.length = 0;
		//是否有莫默认选择项
		if(cDefaultSelect) {
			elementHtml+='<option value="" data-id="请选择"></option>';
			
			//cSelect.get(0).options.add(new Option("请选择",""));
		}
		for(var key=0; key<data.length; key++) {
		//for(var key in data.jobFun) {
			if(selRoot) {
				if(data[key].id == mSelect.attr("value")) {
					elementHtml+='<option value="'+data[key][fv]+'" data-id="'+data[key].id+'">'+data[key].name+'</option>';
					
					//cSelect.get(0).options.add(new Option(data[key].name, data[key][fv]));
				}
				if(data[key].id.toString().substr(0,2) == mSelect.attr("value").substr(0,2) && data[key].id != mSelect.attr("value")) {
					elementHtml+='<option value="'+data[key][fv]+'" data-id="'+data[key].id+'">&nbsp;├-'+data[key].name+'</option>';
					
					//cSelect.get(0).options.add(new Option(' ├-' + data[key].name, data[key][fv]));
				}
			} else {
				if(data[key].id.toString().substr(0,2) == mSelect.attr("value").substr(0,2) && data[key].id != mSelect.attr("value")) {
					elementHtml+='<option value="'+data[key][fv]+'" data-id="'+data[key].id+'">'+data[key].name+'</option>';
					
					//cSelect.get(0).options.add(new Option(data[key].name, data[key][fv]));
				}
			}
		}
		cSelect.html(elementHtml);
	};
	init();
}

//初始化男女，返回html
function initGenderRadio(name) {
	return initRadioOrCheckBox("radio", datajson.sex, name, "id");
}

//初始化婚姻状况，返回html
function initMarriageStatusRadio(name) {
	return initRadioOrCheckBox("radio", datajson.marriageStatus, name, "id");
}

//初始化证件类型，返回html
function initCreTypeRadio(name) {
	return initRadioOrCheckBox("radio", datajson.creType, name, "id");
}

//初始化待遇（如：包食宿，提供住宿）
function initTreatmentCheckBox(name) {
	return initRadioOrCheckBox("checkbox", datajson.payOther, name, "name");
}

//初始化radio或checkbox
function initRadioOrCheckBox(type, data, name, fv) {
	var html = "";
	for(var key=0; key<data.length; key++) {
	//for(var key in data) {
		html += "<input type=\"" + type + "\" id=\"name" + key + "\" name=\"" + name + "\" value=\"" + data[key][fv] + "\" />" + data[key].name;
	}
	return html;
}

//移动指定下拉列表中的项到目标列表中
function moveOption(sourceId, targetId, rootValid, maxLength) {
	//移动元素
	var move=function() {
		//var source = $("#" + sourceId + " option:selected");
		var source = $("#" + sourceId + " option").filter(":selected");
		source.each(function() {
			var sourceValue = $(this).val();
			var sourceText = $(this).text();
			//为兼容地区选择添加dataId
			var dataId = $(this).attr("data-id") == "undefined" ? "" : $(this).attr("data-id");
			//限制移动的最大数量-1为不限制
			if(maxLength != -1 && $("#" + targetId + " option").size() >= maxLength)
				return;
			if(validTarget(sourceValue, $(this))) {
				if(sourceValue.substr(2,2) == "00") {
					$("#" + targetId).prepend("<option value='" + sourceValue + "' data-id='" + dataId + "'>" + sourceText + "</option>");
				} else {
					$("#" + targetId).append("<option value='" + sourceValue + "' data-id='" + dataId + "'>" + sourceText + "</option>");
				}
				//删除正常移动的对象
				$(this).remove();
			}
			//$(this).remove();
		});
	};
	
	//验证目标是否存在
	var validTarget=function(sourceValue, option) {
		var valid = true;
		var target = $("#" + targetId + " option");
		target.each(function() {
			var dataId = $(this).attr("data-id");
			if(sourceValue == $(this).val()) {
				valid = false;
				//删除已经存在的对象
				option.remove();
				return;
			}
			
			//是否验证根对象
			if(rootValid) {
				if(!validRoot(sourceValue, dataId)) {
					valid = false;
					return;
				}
			}
		});
		return valid;
	};
	
	//验证根节点是否存在，如已选择广东省，则不允许选择下面的城市
	var validRoot=function(sourceValue, targetValue) {
		if(sourceValue.substr(0,2) == targetValue.substr(0,2) && (targetValue.substr(2,2) == "00" || sourceValue.substr(2,2) == "00")) {
			return false;
		}
		return true;
	};
	move();
	//$("#" + sourceId + " option:selected").prependTo("#" + targetId);
}

//用户选择组件
function selectUser(textId, hiddenId) {
	$.jBox("iframe:/sys/select/user?textId=" + textId + "&hiddenId=" + hiddenId, {
		id: "select_user",
	    title: "选择用户",
	    width: 730,
	    height: 470,
	    buttons: {}
	});
}

//企业选择组件(isMultiple（true为多选，false为单选)
function selectCom(textId, hiddenId, isMultiple, callback) {
	if(typeof callback == 'undefined'){
		callback = '';
	}
	$.jBox("iframe:/sys/select/com?textId=" + textId + "&hiddenId=" + hiddenId + "&isMultiple=" + isMultiple + "&callback=" + callback, {
		id: "select_company",
	    title: "选择企业",
	    width: 730,
	    height: 470,
	    buttons: {}
	});
}

//职位选择组件(isMultiple（true为多选，false为单选),callback为回调函数名称
function selectPosition(textId, hiddenId, comTextId, comHiddenId, isMultiple) {
	$.jBox("iframe:/sys/select/position?textId=" + textId + "&hiddenId=" + hiddenId + "&comTextId=" + comTextId + "&comHiddenId=" + comHiddenId + "&isMultiple=" + isMultiple, {
		id: "select_position",
	    title: "选择职位",
	    width: 730,
	    height: 470,
	    buttons: {}
	});
}

function selectSite(textId, hiddenId, isMultiple, rightFlag){
	if(typeof rightFlag == 'undefined'){
		rightFlag = true;
	}
	$.jBox("iframe:/sys/select/site?textId=" + textId + "&hiddenId=" + hiddenId + "&isMultiple=" + isMultiple + "&rightFlag=" + rightFlag, {
		id: "select_site",
	    title: "选择站点",
	    width: 540,
	    height: 350,
	    buttons: {}
	});
}

//ajax载入列表数据
function ajaxLoadDataList(url, data, dataContainerId, countContainerId) {
	$.jBox.tip("数据加载中...请稍候...", "loading");
 	$.ajax({
		type: "POST",
		url: url,
		data: data,
		dataType: "html",
		success:function(data){
			$.jBox.closeTip();
			$("#" + dataContainerId).html(data);
			$("#" + countContainerId).html("共" + $("#pagecount").val() + "页" + 
					$("#totalCount").val() + "条记录&nbsp;每页" + $("#pageSize").val() + 
					"条记录&nbsp;当前第" + $("#pagenumber").val() + "页");
		},
		error:function (XMLHttpRequest, textStatus, errorThrown) {
			$.jBox.error('<p style="color:red;padding-top:5px;font-size:14px;">系统正忙,请稍后再试！</p>',"操作提示！");
		}
	});
}

(function ($) {
    $.isEmpty = function (str) {
        if(str == undefined||str ==null||$.trim(str) == ''){
            return true;
        } else {
            return false;
        }
    };
    $.defaultIfEmpty = function (str,defaultStr) {
        return $.isEmpty(str) ? defaultStr : str;
    };
}(jQuery));

(function ($) {
    'use strict';

    var escape = /["\\\x00-\x1f\x7f-\x9f]/g,
        meta = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        hasOwn = Object.prototype.hasOwnProperty;

    /**
     * jQuery.toJSON
     * Converts the given argument into a JSON representation.
     *
     * @param o {Mixed} The json-serializable *thing* to be converted
     *
     * If an object has a toJSON prototype, that will be used to get the representation.
     * Non-integer/string keys are skipped in the object, as are keys that point to a
     * function.
     *
     */
    $.toJSON = typeof JSON === 'object' && JSON.stringify ? JSON.stringify : function (o) {
        if (o === null) {
            return 'null';
        }

        var pairs, k, name, val,
            type = $.type(o);

        if (type === 'undefined') {
            return undefined;
        }

        // Also covers instantiated Number and Boolean objects,
        // which are typeof 'object' but thanks to $.type, we
        // catch them here. I don't know whether it is right
        // or wrong that instantiated primitives are not
        // exported to JSON as an {"object":..}.
        // We choose this path because that's what the browsers did.
        if (type === 'number' || type === 'boolean') {
            return String(o);
        }
        if (type === 'string') {
            return $.quoteString(o);
        }
        if (typeof o.toJSON === 'function') {
            return $.toJSON(o.toJSON());
        }
        if (type === 'date') {
            var month = o.getUTCMonth() + 1,
                day = o.getUTCDate(),
                year = o.getUTCFullYear(),
                hours = o.getUTCHours(),
                minutes = o.getUTCMinutes(),
                seconds = o.getUTCSeconds(),
                milli = o.getUTCMilliseconds();

            if (month < 10) {
                month = '0' + month;
            }
            if (day < 10) {
                day = '0' + day;
            }
            if (hours < 10) {
                hours = '0' + hours;
            }
            if (minutes < 10) {
                minutes = '0' + minutes;
            }
            if (seconds < 10) {
                seconds = '0' + seconds;
            }
            if (milli < 100) {
                milli = '0' + milli;
            }
            if (milli < 10) {
                milli = '0' + milli;
            }
            return '"' + year + '-' + month + '-' + day + 'T' +
                hours + ':' + minutes + ':' + seconds +
                '.' + milli + 'Z"';
        }

        pairs = [];

        if ($.isArray(o)) {
            for (k = 0; k < o.length; k++) {
                pairs.push($.toJSON(o[k]) || 'null');
            }
            return '[' + pairs.join(',') + ']';
        }

        // Any other object (plain object, RegExp, ..)
        // Need to do typeof instead of $.type, because we also
        // want to catch non-plain objects.
        if (typeof o === 'object') {
            for (k in o) {
                // Only include own properties,
                // Filter out inherited prototypes
                if (hasOwn.call(o, k)) {
                    // Keys must be numerical or string. Skip others
                    type = typeof k;
                    if (type === 'number') {
                        name = '"' + k + '"';
                    } else if (type === 'string') {
                        name = $.quoteString(k);
                    } else {
                        continue;
                    }
                    type = typeof o[k];

                    // Invalid values like these return undefined
                    // from toJSON, however those object members
                    // shouldn't be included in the JSON string at all.
                    if (type !== 'function' && type !== 'undefined') {
                        val = $.toJSON(o[k]);
                        pairs.push(name + ':' + val);
                    }
                }
            }
            return '{' + pairs.join(',') + '}';
        }
    };

    /**
     * jQuery.evalJSON
     * Evaluates a given json string.
     *
     * @param str {String}
     */
    $.evalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
        /*jshint evil: true */
        return eval('(' + str + ')');
    };

    /**
     * jQuery.secureEvalJSON
     * Evals JSON in a way that is *more* secure.
     *
     * @param str {String}
     */
    $.secureEvalJSON = typeof JSON === 'object' && JSON.parse ? JSON.parse : function (str) {
        var filtered =
            str
                .replace(/\\["\\\/bfnrtu]/g, '@')
                .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                .replace(/(?:^|:|,)(?:\s*\[)+/g, '');

        if (/^[\],:{}\s]*$/.test(filtered)) {
            /*jshint evil: true */
            return eval('(' + str + ')');
        }
        throw new SyntaxError('Error parsing JSON, source is not valid.');
    };

    /**
     * jQuery.quoteString
     * Returns a string-repr of a string, escaping quotes intelligently.
     * Mostly a support function for toJSON.
     * Examples:
     * >>> jQuery.quoteString('apple')
     * "apple"
     *
     * >>> jQuery.quoteString('"Where are we going?", she asked.')
     * "\"Where are we going?\", she asked."
     */
    $.quoteString = function (str) {
        if (str.match(escape)) {
            return '"' + str.replace(escape, function (a) {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + str + '"';
    };

}(jQuery));

/** * 对Date的扩展，将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
 可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
 Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function (fmt) {
	if (fmt == undefined) {
		fmt = "yyyy-MM-dd"; //默认format
	}
	var o = {
		"M+": this.getMonth() + 1, //月份
		"d+": this.getDate(), //日
		"h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
		"H+": this.getHours(), //小时
		"m+": this.getMinutes(), //分
		"s+": this.getSeconds(), //秒
		"q+": Math.floor((this.getMonth() + 3) / 3), //季度
		"S": this.getMilliseconds() //毫秒
	};
	var week = { //week对应中文字符
		"0": "/u65e5",
		"1": "/u4e00",
		"2": "/u4e8c",
		"3": "/u4e09",
		"4": "/u56db",
		"5": "/u4e94",
		"6": "/u516d"
	};
	//组建 字符串
	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
	}
	if (/(E+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
	}
	for (var k in o) {
		if (new RegExp("(" + k + ")").test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
		}
	}
	return fmt;
};

function longToString(ltime, format) {
	if (format == undefined) {
		format = "yyyy-MM-dd";
	}
	return new Date(ltime).pattern(format);
}
//页面分页搜索功能
var page={
	pageNoName:"pn",
	$pageListPanel:$("#htmlContainer"),
	pageUrl:'',
	loadPageHTML:function(url,data,$pageListPanel){
		$pageListPanel
	},
	search:function($queryForm,url,pn){
		var This=this;
		var p = url.indexOf("?") == -1 ? "?" : "&";
		window.loadPage(url+p+This.pageNoName+'='+pn, $queryForm.serialize(),(this.$panel_edit?this.$pageListPanel:undefined));
	},
	initPageBar:function($page,$queryForm,url,pageOptions){
		var This=this;
		pageOptions.buttonClickCallback=function(pn){This.search($queryForm,url,pn)};
        $page.pager(pageOptions);
	},
	initSearch:function($queryForm,$searchBtn,url){
		var This=this;
		$searchBtn.on("click", function(){
			This.search($queryForm,url,1);
			//绑定查询快捷键
            SearchShortcuts.bindShortcutsByContainer($queryForm,$searchBtn);
		});
	}
}

//文件后缀检测
var testFilePattern = function (fileName, fileTypes) {
	if(fileName != null){
		if (fileName == '') {
			layer.msg("请选择上传文件!",{icon:2});
			return false;
		}
		var file = fileName.match(/[^\/\\]+$/gi)[0];
		var rx = new RegExp("(?:" + fileTypes + ")$", "gi");
		if (!rx.test(file)) {
			layer.msg('只允许上传' + fileTypes.replace(/\|/g, "、") + '格式的文件！',{icon:2});
			return false;
		}
		return true;
	}
	return false;
};
//验证文件域是否为空
function selFile(){
	var errTip = '<label class="error">请选择图片</label>';
	$('input[name="file"]').each(function(k, v){
		if( $(v).nextAll('[type="hidden"]').val() == '' && $(v).parent().css('display') != 'none' ) {
			//console.log($(v).nextAll('[type="hidden"]').attr('id'));
			$(v).parent().append(errTip);
			$(v).change(function(){
				$(this).nextAll('.error').remove();
			});
		}
	});
}
//图片上传方法
function photoUpload(event, inputFile) {
	var $target = $(event.target);
	var fileId = $target.attr('id');
	var fileName = $target.val();
	var fileDir = "com_reg";   //固定目录，新建的话需要后端去配置
	var inputFileName = /([^\/\\]*\.\w*)$/.exec(fileName)[0];
	if (testFilePattern(fileName, "jpg|jpeg|png")) {
		layer.msg('图片上传中...请稍候...', {icon: 16,time: 0});
		$.ajaxFileUpload({
			url: '/upload/' + fileDir + '/' + fileId + '/up_json',   //调用上传组件
			secureuri: false,
			fileElementId: fileId,  //文件上传空间的id属性  <input type="file" id="file" name="file" />
			dataType: 'json',//返回值类型 一般设置为json
			success: function (dataObj, status) {
				layer.closeAll();
				if (typeof(dataObj.error) != 'undefined') {
					layer.msg(dataObj.error,{icon:2});
				} else {
					//添加预览按钮
					var fileLabel = $('#'+inputFile).parent(),
						previewBtnHtml = '<a href="javascript:;" onclick="preview(this)" class="preview-btn">预览</a>';
					fileLabel.find('.preview-btn').remove(); //对于原有的预览按钮要先删除
					fileLabel.append($(previewBtnHtml));
					//添加预览节点
					if( $('#imgView').length == 0 ) {
						var imgHtml = '<img id="imgView" src="" alt="预览"  style="display: none;" />';
						$('#imgView').remove();
						$('body').append(imgHtml);
					}

					$('#'+inputFile).removeClass("error").val(dataObj.fileUrl).prev(); // 将图片在服务器中的路径赋值给隐藏域从而入库
					$('[for="'+inputFile+'"]').remove();
					$('#imgView').attr('src', dataObj.fileUrl); //给预览标签填写图片路径
					$('#'+inputFile).prevAll('.p-path').text(inputFileName); //注册页用到
					layer.msg(inputFileName +"上传成功！" ,{icon:1});
				}
			},
			error: function (data, status, e) {
				alert(e);
				return false;
			}
		});
	}
}

//预览图片
function preview(obj) {
	//添加预览节点
	if( $('#imgView').length == 0 ) {
		var imgHtml = '<img id="imgView" src="" alt="预览"  style="display: none;" />';
		$('#imgView').remove();
		$('body').append(imgHtml);
	}
	if ( typeof(obj) != 'undefined' ) {
		var url = $(obj).parent().find('input[type="hidden"]').val();
		$("#imgView").attr("src", url);
	}
	if ( $("#imgView").attr("src") ) {
		layer.open({
			type: 1,
			title: false,
			closeBtn: true,
			//area: ['600px', '600px'],
			area: '600px',
			offset: '20px',
			skin: 'layui-layer-nobg', //没有背景色
			shadeClose: true,
			content: $("#imgView")
		});
	}
}

var getBankList=function($obj){
	var bankName=$obj.data("bank");
	$.ajax({
		type:"post",
		url:"/finance/common/getallbank",
		async:false,
		dataType:"json",
		success:function(data){
			var list=data.items;
			var len=list.length;
			var html='<select id="bankName" name="bankName" style="padding:6px 9px;"><option value="">选择银行</option>';
			for(var i=0;i<len;i++){
					if(list[i].name!="平安银行"){
						html +='<option value="'+list[i].name+'" '+(bankName==list[i].name ? "selected" : "")+'>'+list[i].name+'</option>';
					}
				//html +='<option value="'+list[i].signType+'" '+(bankName==list[i].name ? "selected" : "")+'>'+list[i].name+'</option>';
			}
			html +='</select>';
			$obj.html(html);
		}
	});
};


//银行选择
var bankSelectBox=function($obj,$bankInput,type){
	//var t = type==null ? true : type;
	getBankList($obj);
	/*var $bankCardImgPan=$("#bankCardImgPan");
	var $bankInputPan=$("#bankInputPan");*/
	$("#bankName").change(function(){
		var bank=$(this).val();
		bankChange(bank);
	}).change();
	
	//其他银行选择
	$("#bankDetailName").on("click",function () {
		var $this=$(this);
		var $p=$this.closest(".bank");
		bankselector.box(function($item) {
			var branchName=$item.data("name");
			var bankCode=$item.val();
			var bank=$item.data("bank");
			var bankId=$item.data("bankid");
			$this.val(branchName);
			$p.find('[name="bankId"]').val(bankId);
			$p.find('[name="bankCode"]').val(bankCode);
			$p.find('[name="bankRealName"]').val(bank);
		});
	});

	/*输入银行卡号自动选择银行，目前暂不使用*/
	/*if(t){
		var getBankName=function(){
			var bankno=$bankInput.val();
			$.ajax({
				type:"post",
				url:"/finance/common/getbankcode",
				data:{"bankAccount":bankno},
				dataType:"json",
				success:function(data){console.log(data.succ);
					if(data.succ){
						//console.log(data.item.bankName);
						$obj.find("select").val(data.item.bankName);
					}else{
						$obj.find("select").val("");
					}
				}
			});
		};
		$bankInput.blur(function(){
			setTimeout(function(){
				if(!$bankInput.is("error")){
					getBankName();
				}
			},50);
		});
		setTimeout(function() {
			if ($bankInput.val() != "") {
				$bankInput.focus().blur();
			}
		},50);
	}*/
};

//银行类型切换事件
var bankChange = function(type){
	switch(type){
		case ("1") :
			$(".bank").not(".zxBank").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".zxBank").show().find("input,select").prop("disabled",false);
			break;
		case ("2") :
			$(".bank").not(".pnYibao").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".pnYibao").show().find("input,select").prop("disabled",false);
			break;
		case ("中信银行") :
			$(".bank").not(".zxBank").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".zxBank").show().find("input,select").prop("disabled",false);
			break;
		case ("平安易宝") :
			$(".bank").not(".pnYibao").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".pnYibao").show().find("input,select").prop("disabled",false);
			break;
		/*case ("3") :
			$(".bank").not(".pnBank").hide().find("input").prop("disabled",true);
			$(".pnBank").show().find("input").prop("disabled",false);
			break;*/
		case ("广发银行存管") :
			//广发银行业务
			$(".bank").not(".gfBank").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".gfBank").show().find("input,select").prop("disabled",false);

			/*$(".bank").show().find("input").prop("disabled",false);
			$(".bank").filter(".pnYibao").hide().find("input").prop("disabled",true);
			$(".gfBank").show().find("input").prop("disabled",false);*/
			break;
		default:
			//中信银行
			$(".bank").not(".zxBank").hide().find("input,select").not(".notDisabled").prop("disabled",true);
			$(".zxBank").show().find("input,select").prop("disabled",false);
			break;
	}
};
/*!
 * 功能：图片是否加载完成
 */
loadImage = function(url, callback) {
	var img = new Image(); //创建一个Image对象，实现图片的预下载
	img.onload = function () { //图片下载完毕时异步调用callback函数。
		img.onload=null;
		try {
			callback(img);//将回调函数的this替换为Image对象
		}catch(err){
			layer.alert('<p class="cRed">图片不存在</p>',{title:"温馨提示",icon:0});
		}
	};
	img.onerror=function(){
		layer.alert('<p class="cRed">此图片无效或不存在！</p>',{title:"温馨提示",icon:0});
	};
	img.src = url;
};

/*!
 * 功能：缩略居中计算
 * 返回缩小尺寸和在坐标位置,top,left,width,height四个对象值
 * width,height为原尺寸；maxWidth, maxHeight为在这个尺寸下缩小。
 * 2013-03-20
 */
zoomParam = function ( maxWidth, maxHeight, width, height){
	var param = {top:0, left:0, width:width, height:height};
	if( width>maxWidth || height>maxHeight ){
		rateWidth = width / maxWidth;
		rateHeight = height / maxHeight;
		if( rateWidth > rateHeight ){
			param.width =  maxWidth;
			param.height = Math.round(height / rateWidth);
		}else{
			param.width = Math.round(width / rateHeight);
			param.height = maxHeight;
		}
	}
	param.left = Math.round((maxWidth - param.width) / 2);
	param.top = Math.round((maxHeight - param.height) / 2);
	return param;
};

if($(".selectSetValue").length>0) {
	$(".selectSetValue").each(function(){
		var val = $(this).data("value");
		if(val!=""){
			$(this).val(val);
		}
	});
}